<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\plugin;

use app\common\plugin\MainApiService;
use GuzzleHttp\Client;

/**
 * 插件用户认证控制器
 */
class Auth extends Base
{
    private $mainApiService;
    private $loginManager;

    public function __construct()
    {
        parent::__construct();
        $this->mainApiService = new MainApiService();
        $this->loginManager   = new LoginManager();
    }

    /**
     * 用户登录
     */
    public function login()
    {
        try {
            $email    = input('email');
            $password = input('password');


            if (empty($email) || empty($password)) {
                return $this->error('邮箱和密码不能为空');
            }

            // 调用main项目登录接口
            $loginResult = $this->mainApiService->login($email, $password);

            // 登录成功，保存到缓存文件
            $token = $this->loginManager->saveLogin($email, $loginResult['token'], $loginResult['user']);

            return $this->success('登录成功', [
                'token'     => $token,
                'user_info' => $loginResult['user'],
                'email'     => $email
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        try {
            $token = $this->getUserToken();
            if (empty($token)) {
                return $this->error('请先登录', []);
            }

            $userInfo = $this->getUserInfoFromMain($token);
            return $this->success('获取成功', $userInfo);
        } catch (\Exception $e) {
            return $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 用户退出登录
     */
    public function logout()
    {
        try {
            $this->loginManager->removeLogin();
            return $this->success('退出成功');
        } catch (\Exception $e) {
            return $this->error('退出失败：' . $e->getMessage());
        }
    }

    /**
     * 检查登录状态
     */
    public function checkLogin()
    {
        $loginData = $this->loginManager->getLogin();

        if ($loginData) {
            // 刷新登录状态
            $this->loginManager->refreshLogin();

            return $this->success('已登录', [
                'is_login'  => true,
                'user_info' => $loginData['user_info'],
                'token'     => $loginData['token'],
                'email'     => $loginData['email']
            ]);
        } else {
            return $this->success('未登录', [
                'is_login' => false
            ]);
        }
    }

    /**
     * 调用main项目登录接口
     */
    private function loginToMain($email, $password)
    {
        $url = $this->getMainApiUrl('/api/service/login');

        $params = [
            'email'    => $email,
            'password' => $password
        ];

        return httpRequest($url, $params, 'POST');
    }

    /**
     * 从main项目获取用户信息
     */
    private function getUserInfoFromMain($token)
    {
        $url = $this->getMainApiUrl('/api/auth/user');

        $params = ['token' => $token];

        $response = httpRequest($url, $params);

        if ($response['code'] !== 1) {
            throw new \Exception($response['msg'] ?? '获取用户信息失败');
        }

        return $response['data'] ?? [];
    }

    /**
     * 调用main项目退出接口
     */
    private function logoutFromMain($token)
    {
        $url = $this->getMainApiUrl('/api/auth/logout');

        $params = ['token' => $token];

        return httpRequest($url, $params, 'POST');
    }

}
